package com.qf.data.service;

import com.qf.common.constant.CacheConstant;
import com.qf.data.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author 千锋健哥
 */
@Service
public class HeartBeatServiceImpl implements HeartBeatService{

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void saveHeartBeat(String productKey, String deviceKey) {
        //获取当前时间的时间戳
        long value = System.currentTimeMillis();

        String key = CacheConstant.Entity.DEVICE + CacheConstant.Suffix.PING
                      + "_" +productKey + "_" + deviceKey;
        redisUtil.setKey(key, value, 30, TimeUnit.SECONDS);
    }

    @Override
    public Boolean findState(String productKey, String deviceKey) {
        String key = CacheConstant.Entity.DEVICE + CacheConstant.Suffix.PING
                + "_" +productKey + "_" + deviceKey;

        Long value = redisUtil.getKey(key, Long.class);

        if (value == null) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public Integer onLineCount(String productKey) {
        String key = CacheConstant.Entity.DEVICE + CacheConstant.Suffix.PING
                + "_" +productKey + "*" ;

        //查询满足条件的所有的key的集合
        Set<String> keys = redisUtil.keys(key);
        if (keys != null) {
            return keys.size();
        } else {
            return 0;
        }

    }

}
